<template>
  <div v-drag>
    <div class="mask" @click="closePopup(false)"></div>
    <div class="edit_box" id="change_width" v-loading="loading">
      <div class="box_head">
        <p>新增退桶单</p>
        <i @click="closePopup(false)"></i>
      </div>
      <div class="box_body">
        <div v-if="step===1">
          <div class="line">
            <span class="lab"><i class="mark_icon" v-if="!$route.query.userId">*</i>用户：</span>
            <div>
              <userSelect @listenToUser="getAddress" :uId="userId" v-if="!$route.query.userId"/>
              <p v-else>{{$route.query.username}}</p>
            </div>
          </div>
          <div class="line">
            <span class="lab"><i class="mark_icon">*</i>配送地址：</span>
            <div>
              <el-select
                filterable
                v-model="address"
                @change="clearNum"
                placeholder="请选择退桶地址">
                <el-option
                  v-for="(item,index) in addressOption"
                  :key="index"
                  :label="item.address"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </div>
        </div>

        <div v-else>
          <div class="line">
            <div class="g-mt-10">
              <a class="common_btn el-icon-delete" @click="clearNum()"></a>
              <a class="common_btn el-icon-circle-plus-outline" @click="addProNum()"></a>
            </div>
          </div>
          <div>
            <div v-for="(link,index) in proNum" :key="index" class="input-box g-mb-10" id="link">
              <div class="content_box">
                <div :class="(errIndex == index && errKey === 'name')? 'error_border select_box' : 'select_box'" ref="input">
                  <el-select
                    filterable
                    ref="linkName"
                    @focus="errIndex = undefined;tipText=''"
                    :popper-append-to-body="false"
                    v-model="proNum[index].productId"
                    @change="getProductInfo($event,index)"
                      placeholder="请选择商品">
                    <el-option
                      v-for="(item,index) in list"
                      :key="index"
                      :label="item.productName"
                      :value="item.productId">
                    </el-option>
                  </el-select>
                </div>
                <div class="info_box" v-if="proNum[index].productId">
                  <div class="info_item">
                    <span class="lab">抵押数：</span>
                    <div>
                      <el-input-number v-model="proNum[index].pledgeNumber" disabled></el-input-number>
                    </div>
                  </div>
                  <div class="info_item">
                    <span class="lab">抵押金：</span>
                    <div>
                      <el-input-number v-model="proNum[index].pledgeMoney" disabled></el-input-number>
                    </div>
                  </div>
                  <div class="info_item" >
                    <span class="lab">退桶数：</span>
                    <div style="border-radius: 5px;" :style="{border:errIndex == index && errKey === 'number' ? '1px solid #c60000' : ''}">
                      <el-input-number @focus="errIndex=undefined;tipText=''" v-model="proNum[index].numbers" :min="0" :max="proNum[index].pledgeNumber"></el-input-number>
                    </div>
                  </div>
                </div>

<!--                <div class="num_box"  :style="{border:errIndex == index && errKey === 'number' ? '1px solid #c60000' : ''}" >-->
<!--                  <span class="minus_btn" @click="deleteProduct(index)">-->
<!--                    <i class="el-icon-minus" :class="{'lose':parseFloat(proNum[index].numbers) <=1}"></i>-->
<!--                  </span>-->
<!--                  <input class="num_show" type="number" v-model="proNum[index].numbers" min="0" @focus="errIndex = undefined;tipText=''"/>-->
<!--                  <span class="plus_btn" @click="addProduct(index)">-->
<!--                    <i class="el-icon-plus"></i>-->
<!--                  </span>-->
<!--                </div>-->
                <!--只有一条的时候，不显示删除-->
                <i class="delSingle el-icon-remove-outline" @click="delSingleInput(index)"></i>
              </div>
            </div>
          </div>
        </div>
        <p class="error_line" :class="{'specail_error':step===2}">{{ tipText }}</p>
      </div>
      <div class="box_foot" v-if="step===1">
        <span @click="closePopup(false)">取消</span>
        <span @click="setStep(2)">下一步</span>
      </div>
      <div class="box_foot" v-else>
        <span @click="step=1;tipText='';">上一步</span>
        <span @click="judgeInfo">确定</span>
      </div>
    </div>
  </div>
</template>

<script>
import {getAllUserProduct} from "@/api/data/user/product";
import {getAllAddress} from "@/api/data/user/address";
import userSelect from '../../../components/user/index'
import {addBucketOrder} from "../../../api/data/user/productReturn";
import {getProductNumber} from "@/api/data/user/change";

export default {
  components:{
    userSelect
  },
  data() {
    return {
      step: 1,
      loading: false,
      tipText: '',
      userId: '',
      list: [],
      address: '',
      addressOption: [],
      proNum: [{
        numbers: '',
        productId: '',
      }],
      test: [],
      delNum: null,
      errIndex: undefined,
      errKey:undefined
    }
  },
  mounted() {
    if (this.$route.query.userId){
      this.userId = this.$route.query.userId;
      this.getAddress(this.$route.query.userId);
    }
  },
  methods: {
    getProduct() {
      getAllUserProduct({userId:this.userId}).then((res) => {
        this.list = res ? res : [];
      })
    },
    // 获取用户id和地址
    getAddress(e) {
      this.userId = e;
      this.tipText = '';
      this.address = '';
      getAllAddress({userId: e}).then(res => {
        this.addressOption = res ? res : [];
      }).catch((e) => {
        this.addressOption = [];
      })
      this.clearNum();
    },

    setStep(type) {
      if (type === 2) {
        if (this.userId === '') {
          this.tipText = '请先选择退桶用户'
        } else if (this.address === '') {
          this.tipText = '请先选择退桶地址'
        } else {
          this.step = type;
          this.isFinal = false;
          this.getProduct();
        }
      }
    },
    //根据选择商品获取抵押信息
    getProductInfo(id, index) {
      let params = {
        userId: this.userId,
        productId: id
      }
      getProductNumber(params).then((res) => {
        if (res) {
          this.proNum[index].pledgeMoney = res.pledgeMoney ? res.pledgeMoney : 0;
          this.proNum[index].pledgeNumber = res.pledgeNumber ? res.pledgeNumber : 0;
          this.proNum[index].numbers = res.pledgeNumber;
        }
      })
    },
    judgeInfo() {
      let that = this;
      that.tipText = '';
      for (let i = 0; i < that.proNum.length; i++) {
        for (let j = i + 1; j < that.proNum.length; j++) {
          if (that.proNum[i].productId === that.proNum[j].productId) {
            that.errIndex = i;
            that.errKey = 'name'
            that.tipText = '不能选择两种相同的商品';
            return;
          }
        }
      }
      that.judgeNum();
    },
    judgeNum() {
      let that = this;
      for (let i = 0; i < that.proNum.length; i++) {
        let data = that.proNum[i]
        if(data.numbers === '' || data.numbers === 0) {
          that.errIndex = i;
          that.errKey = 'number'
          that.tipText = '请输入数量';
          return;
        }
      }

      that.createOrder();
    },

    closePopup(refresh) {
      this.$emit('listenToChild', {refresh:refresh})
    },

    createOrder() {
      this.loading = true;
      let param = {
        userId: this.userId,
        addressId: this.address,
        productInfo: this.proNum
      }
      console.log(param,'啦啦啦啦')
      return;
      addBucketOrder(param).then(res => {
        this.$message.success({
          message: '操作成功',
          duration: 1500
        });
        this.closePopup(true);
        this.loading = false;
      }).catch((e) => {
        this.loading = false;
      })
    },

    deleteProduct(index) {
      let num = this.proNum[index].numbers;
      this.proNum[index].numbers = parseFloat(num) <= 1 ? 0 : parseFloat(num) - 1;
    },

    addProduct(index) {
      let num = parseFloat(this.proNum[index].numbers)
      this.proNum[index].numbers = num + 1;
    },

    /*添加*/
    addProNum() {
      let cope = {numbers: '', productId: ''};
      this.proNum.push(cope);
      this.tipText = '';
    },

    /*清除*/
    clearNum() {
      this.proNum = [];
      for (const i in this.$refs.input) {
        this.$refs.input[i].className = ''
      }
      let cope = {numbers: '', productId: ''};
      this.proNum.push(cope);
      this.tipText = '';
    },

    // 单个删除
    delSingleInput(index) {
      this.proNum.splice(index, 1);
      this.tipText = '';
    },

    showDel(index) {
      this.delNum = index + 1;
      /*只有一条的时候，不加删除文字，可清空*/
      if (this.proNum.length == 1) {
        this.delNum = null
      }
    },
  }
}
</script>

<style scoped>
.box_body {
  min-height: 400px;
}
.content_box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  position: relative;
}
.content_box .select_box {
  width: 100%;
}
.info_box {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}
.info_box .info_item {
  width: 47%;
  height:40px;
  padding:0 15px 15px 0;
}
.info_item {
  display: flex;
  align-items: center;
  margin-top:20px;
}
.info_item .lab {
  width:100px;
  display: block;
  font-size: 15px;
}
.input_box {
  display: flex;
  align-items: center;
  position: relative;
}

.line .link-input {
  line-height: 36px;
  border-radius: 4px;
  outline: none;
}

* {
  box-sizing: border-box;
}

.g-mb-10 {
  margin-bottom: 10px;
}

.g-ml-15 {
  margin-left: 15px;
}

a {
  text-decoration: none;
}

.link-txt {
  margin-right: 12px;
  width: 15px;
  float: left;
}

.link-input {
  width: 250px;
  height: 36px;
  background-color: #ffffff;
  border-radius: 2px;
  border: solid 1px #dcdcdc;
  padding-left: 15px;
  float: left;
  display: block;
  font-size: 14px;
  padding-right: 35px;
}

.common_btn {
  font-size: 24px;
  cursor: pointer;
  color: #6687f9;
  margin-right: 5px;
}

.delSingle {
  position: absolute;
  top: 10px;
  right: 18px;
  cursor: pointer;
  font-size: 22px;
  color: #e40000;
}

.num_box {
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  overflow: hidden;
  margin-left: 30px;
}

.minus_btn, .plus_btn {
  width: 34px;
  display: inline-block;
  height: 34px;
  line-height: 34px;
  text-align: center;
  cursor: pointer;
}

.minus_btn i, .plus_btn i {
  color: #6687f9;
}

.minus_btn {
  border-right: 1px solid #DCDFE6;
}

.plus_btn {
  border-left: 1px solid #DCDFE6;
}

.lose {
  color: #DCDFE6 !important;
}

.num_show {
  max-width: 80px;
  min-width: 40px;
  line-height: 34px;
  text-align: center;
  border: none;
  outline: none;
}

.limit_box {
  margin-top: 10px;
  font-size: 14px;
  color: #6687f9;
}

.specail_error {
  padding-left: 0;
  margin-top: 30px;
}
</style>
